package com.hanxiaozhang.redismysqlconsistent.service.impl;

import com.hanxiaozhang.common.domain.DictDO;
import com.hanxiaozhang.common.service.DictService;
import com.hanxiaozhang.config.RedisUtil;
import com.hanxiaozhang.redismysqlconsistent.service.CacheConsistentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/10/12
 * @since 1.0.0
 */
public class CacheConsistentServiceImpl implements CacheConsistentService {

    public static final String CACHE_DICT_ID_PREFIX = "hanxiaozhang_dict_%s";

    public static final Integer SLEEP_SECONDS_TIME = 2;

    @Autowired
    private DictService dictService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public DictDO query(Long id) {
        String key = String.format(CACHE_DICT_ID_PREFIX, id);
        DictDO dict = redisUtil.get(key, DictDO.class);
        if (dict == null) {
            dict = dictService.get(id);
            redisUtil.set(key, dict);
        }
        return dict;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DictDO dict) {
        String key = String.format(CACHE_DICT_ID_PREFIX, dict.getId());
        redisUtil.delete(key);
        dictService.update(dict);
        // 异步执行
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(SLEEP_SECONDS_TIME);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            redisUtil.delete(key);
            return true;
        });
    }

}
